package com.chen.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.chen.gulimall.auth.feign.MemberFeignService;
import com.chen.gulimall.auth.feign.SmsSendCodeFeign;
import com.chen.gulimall.auth.vo.UserLoginVo;
import com.chen.gulimall.auth.vo.UserRegisterVo;
import com.chen.gulimallcommon.common.exception.ExceptionCodeEnum;
import com.chen.gulimallcommon.common.utils.R;
import com.chen.gulimallcommon.common.vo.MemberRespVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class RegController {

    @Autowired
    SmsSendCodeFeign smsSendCodeFeign;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/sms/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone) {


        String oldCode = redisTemplate.opsForValue().get("sms:code:" + phone);

        //判断当前验证码的时间超过一分钟了没有，没有则返回error，有则重新获取验证码
        if (!StringUtils.isEmpty(oldCode)) {
            long oldTime = Long.parseLong(oldCode.split("_")[1]);
            if (System.currentTimeMillis() - oldTime < 60000) {
                return R.error(ExceptionCodeEnum.SMS_CODE_EXCEPTION.getCode(),ExceptionCodeEnum.SMS_CODE_EXCEPTION.getMessage());
            }
        }
        String code = UUID.randomUUID().toString().substring(0,5);
        redisTemplate.opsForValue().set("sms:code:" + phone,code + "_" + System.currentTimeMillis(),5, TimeUnit.MINUTES);
        smsSendCodeFeign.sendCode(phone,code);
        return R.ok();
    }




    @PostMapping("/regist")
    public String isRegister(@Valid UserRegisterVo userRegisterVo, BindingResult result, RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            //使用的session会话
            redirectAttributes.addFlashAttribute("errors",errors);

            //使用重定向方式，防止前端页面重复提交，因为前端在次点击时发送action的路径，而重定向是回到表单页面
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        String code = userRegisterVo.getCode();
        String oldCode = redisTemplate.opsForValue().get("sms:code:" + userRegisterVo.getPhone());
        if (!StringUtils.isEmpty(oldCode)) {
            oldCode = oldCode.split("_")[0];
            if (code.equals(oldCode)) {
                //删除旧的验证码
                redisTemplate.delete("sms:code:" + userRegisterVo.getPhone());

                //进行远程调用
                R regist = memberFeignService.regist(userRegisterVo);

                if (regist.getCode() == 0) {
                    return  "redirect:http://auth.gulimall.com/login.html";
                } else {
                    //远程调用保存用户数据失败
                    Map<String,String> errors = new HashMap<>();
                    errors.put("msg","保存用户数据失败");
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }

            } else {
                //说明验证码不匹配
                Map<String,String> error = new HashMap<>();
                error.put("code","验证码不匹配");
                redirectAttributes.addFlashAttribute("errors",error);

            }
        } else {
           //说明验证码不存在或者已经过期
           Map<String,String> error = new HashMap<>();
           error.put("code","验证码不存在或者已经过期");
           redirectAttributes.addFlashAttribute("errors",error);
           return "redirect:http://auth.gulimall.com/reg.html";
        }

        return "redirect:/login.html";


    }

    @GetMapping("/login.html")
    public String log(HttpSession session) {
        Object user = session.getAttribute("loginUser");

        if (user != null) {
            return "redirect:http://gulimall.com";
        }

        return "login";
    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session) {
        R login = memberFeignService.login(vo);

        if (login.getCode() == 0) {

            session.setAttribute("loginUser",login.getData(new TypeReference<MemberRespVo>() {}));

            return "redirect:http://gulimall.com";
        } else {
            Map<String,String> error = new HashMap<>();
            error.put("msg",(String) login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",error);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
